package com.cocostudio.erpapp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnKeyListener;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.ZoomDensity;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.amo.demo.wheelview.NumericWheelAdapter;
import com.amo.demo.wheelview.OnWheelChangedListener;
import com.amo.demo.wheelview.WheelView;
import com.cocostudio.erpapp.adapter.DeptmentAdapter;
import com.cocostudio.erpapp.common.Debug;
import com.cocostudio.erpapp.utils.Constant;
import com.cocostudio.erpapp.utils.UIHelper;
import com.cocostudio.erpapp.utils.WebServiceUtils;
import com.cocostudio.erpapp.vo.ErpDeptment;
import com.cocostudio.erpapp.vo.WSHistorySaleResult;
import com.cocostudio.erpapp.vo.WSRealTimeSalesResult;
import com.cocostudio.erpapp.web.CustomWebChromeClient;
import com.cocostudio.erpapp.R;
import com.google.zxing.client.android.CaptureActivity;

public class HistorySalesActivity extends CustomFragmentActivity {
    private static final String TAG = "HistorySalesActivity";
    private static View searchView;
    private Dialog dialog;
    private static int START_YEAR = 2021, END_YEAR = 2120;
    public static final int SCAN_CODE = 1;


    private WebView webView;
    private EditText search_startdate;
    private EditText search_enddate;

    private String showtype;
    private int deptlevel;
    private String deptid;
    private String categorylevel;
    
    private EditText search_product_name;
    private EditText search_product_size;
    private EditText search_dept_code;
    //private EditText search_dept_level;
    private EditText search_product_code;
    private EditText search_product_barcode;

    private RadioGroup search_showtype;
    private RadioGroup search_dept_level;
    private RadioGroup search_category_level;

    private LinearLayout cell_dept_code;
    private LinearLayout cell_dept_level;
    private LinearLayout cell_product;
    private LinearLayout cell_barcode;
    private LinearLayout cell_category_level;

    private Spinner search_dept_code_spinner;
    private Spinner search_showtype_spinner;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (Debug.LOGD) {
            Log.d(TAG, "onCreate.");
        }
        super.onCreate(savedInstanceState);
        initView();


    }

    public void onStartDate(View view){
        showDatePicker("请选择开始日期",search_startdate);
    }
    public void onEndDate(View view){
        showDatePicker("请选择结束日期",search_enddate);
    }

    public void onScanBarCode(View view){
        Intent intent = new Intent(HistorySalesActivity.this, CaptureActivity.class);
        startActivityForResult(intent, SCAN_CODE);
    }

    
    private void initCategoryUI() {
        search_category_level = (RadioGroup)findViewById(R.id.categorylevel_radiogroup);
        search_category_level.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                int btnid = group.getCheckedRadioButtonId();
                switch (btnid) {
                case R.id.categorylevel1:
                   HistorySalesActivity.this.categorylevel ="1";
                    break;
                case R.id.categorylevel2:
                    HistorySalesActivity.this.categorylevel="2";
                    break;
                case R.id.categorylevel3:
                    HistorySalesActivity.this.categorylevel="3";
                    break;
                case R.id.categorylevel4:
                    HistorySalesActivity.this.categorylevel="4";
                    break;
                default:
                    break;
                }
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case SCAN_CODE:
            TextView scanResult = (TextView) findViewById(R.id.search_product_barcode);
            if (resultCode == RESULT_OK) {
                String result = data.getStringExtra("scan_result");
                scanResult.setText(result);
                onSearchClicked(null);
            } else if (resultCode == RESULT_CANCELED) {
                scanResult.setText("");
            }
            break;
        default:
            break;
        }
    }

    public void onSearchClicked(View view) {

        if (search_startdate.getText().toString().trim().length()<9 )
        {
            UIHelper.showAlert(this,"请确认开始日期正确");
            search_startdate.setFocusable(true);
            return;
        }
         if (search_enddate.getText().toString().trim().length()<9 )
         {
             UIHelper.showAlert(this,"请确认结束日期正确");
             search_enddate.setFocusable(true);
             return;
         }
         
         if ( this.showtype.equals("4") ){
             if ( (search_product_barcode.getText().toString().trim().length()==0) &&
                     (search_product_code.getText().toString().trim().length()==0)   
                     )
             {
                 UIHelper.showAlert(this,"请确认商品信息输入正确");
                 search_product_code.setFocusable(true);
                 return;
             }
         }

        try {
            //从接口获取信息
            pdg = ProgressDialog.show(HistorySalesActivity.this, "温馨提示", "数据请求中，请稍后！");
            pdg.setCancelable(true);
            pdg.setCanceledOnTouchOutside(true);
            webView.loadUrl( Constant.urlprefix+ "history_sales.html");
            pdg.dismiss();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


    public String getFromAssets(String fileName){
        String Result="";
        try {
             InputStreamReader inputReader = new InputStreamReader( getResources().getAssets().open(fileName) );
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line="";
             Result="";
            while((line = bufReader.readLine()) != null)
                Result += line;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result;
    }

    private void initView() {
        
        this.showtype = "1";
        this.deptlevel=1;
        this.categorylevel = "1";
        this.deptid = "01";
        

        setContentView(R.layout.activity_history_sales);

        setTitle(R.string.title_history_sale);

        setLeftButtonDrawable(R.drawable.btn_home);

        searchView = findViewById(R.id.search_component);

        search_startdate= (EditText)findViewById(R.id.search_startdate);
        search_enddate = (EditText)findViewById(R.id.search_enddate);

        search_dept_code_spinner= (Spinner)findViewById(R.id.search_dept_code);
        search_product_code= (EditText)findViewById(R.id.search_product_code);
         search_product_barcode=(EditText)findViewById(R.id.search_product_barcode);

         cell_dept_code  = (LinearLayout)findViewById(R.id.ui_cell_dept_code);
         cell_dept_level = (LinearLayout)findViewById(R.id.ui_cell_dept_level);
         cell_product = (LinearLayout)findViewById(R.id.ui_cell_product_code );
         cell_barcode = (LinearLayout)findViewById(R.id.ui_cell_barcode);
         cell_category_level = (LinearLayout)findViewById(R.id.ui_cell_category_level);
         search_dept_level = (RadioGroup)findViewById(R.id.deptlevel_radiogroup);



        initShowTypeUI();

        initDeptUI();

        initCategoryUI();
        
        initWebViewUI();

        search_product_code.setText("");

   }


    
    private void initWebViewUI() {
        webView = (WebView) findViewById(R.id.detail_result_webview);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setSupportZoom(false);
        webView.setFocusableInTouchMode(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebChromeClient( new CustomWebChromeClient());
        webView.addJavascriptInterface(this, "android");
    }

    private void initDeptUI() {
        
        search_dept_code_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            
                   ErpDeptment item = (ErpDeptment) search_dept_code_spinner.getItemAtPosition(position);
                    
                    HistorySalesActivity.this.deptid=item.getCode();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent){
                Log.d(HistorySalesActivity.TAG, "select onNothing");
            }
        });
        
        search_dept_level.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                int btnid = group.getCheckedRadioButtonId();
                switch (btnid) {
                case R.id.deptlevel1:
                    HistorySalesActivity.this.deptlevel=1;
                    break;
                case R.id.deptlevel2:
                    HistorySalesActivity.this.deptlevel=2;
                    break;
                case R.id.deptlevel3:
                    HistorySalesActivity.this.deptlevel=3;
                    break;
                case R.id.deptlevel4:
                    HistorySalesActivity.this.deptlevel=4;
                    break;
                default:
                    break;
                }
                
                DeptmentAdapter deptAdapter = new DeptmentAdapter(HistorySalesActivity.this, WebServiceUtils.buildDeptList(  
                          HistorySalesActivity.this.deptlevel ));
                search_dept_code_spinner.setAdapter(deptAdapter);
            }
        });
        
        
        if( ! WebServiceUtils.checkHasDeptLevel(1)){
            ((RadioButton)findViewById(R.id.deptlevel1)).setVisibility(View.GONE);
            this.deptlevel=2;
            ((RadioButton)findViewById(R.id.deptlevel2)).setChecked(true);
        }
        if( ! WebServiceUtils.checkHasDeptLevel(2)){
            ((RadioButton)findViewById(R.id.deptlevel2)).setVisibility(View.GONE);
            this.deptlevel=3;
            ((RadioButton)findViewById(R.id.deptlevel3)).setChecked(true);

        }
        if( ! WebServiceUtils.checkHasDeptLevel(3)){
            ((RadioButton)findViewById(R.id.deptlevel3)).setVisibility(View.GONE);
            this.deptlevel=4;
        }
        if( ! WebServiceUtils.checkHasDeptLevel(4))
            ((RadioButton)findViewById(R.id.deptlevel4)).setVisibility(View.GONE);
        
        
        
        if (this.deptlevel==1)
            ((RadioButton)findViewById(R.id.deptlevel1)).setChecked(true);
        if (this.deptlevel==2)
            ((RadioButton)findViewById(R.id.deptlevel2)).setChecked(true);
        if (this.deptlevel==3)
            ((RadioButton)findViewById(R.id.deptlevel3)).setChecked(true);
        if (this.deptlevel==4)
            ((RadioButton)findViewById(R.id.deptlevel4)).setChecked(true);
        
        DeptmentAdapter deptAdapter1 = new DeptmentAdapter(HistorySalesActivity.this, WebServiceUtils.buildDeptList(  
                HistorySalesActivity.this.deptlevel ));

      search_dept_code_spinner.setAdapter(deptAdapter1);
    }

    private void initShowTypeUI() {
        search_showtype_spinner = (Spinner)findViewById(R.id.search_showtype_spinner);
        String[] mshowItems = new String[]{"分部门","分品牌","分类别","单品","分供应商"};

        ArrayAdapter<String> _Adapter_showtype=new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, mshowItems);
        search_showtype_spinner.setAdapter(_Adapter_showtype);
        search_showtype_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {  
            
                HistorySalesActivity.this.showtype = Integer.toString(position+1);

            //3+1==按单品
            if( 4 == (position+1) ){

                HistorySalesActivity.this.cell_product.setVisibility(View.VISIBLE);
                HistorySalesActivity.this.cell_barcode.setVisibility(View.VISIBLE);
                HistorySalesActivity.this.cell_dept_code.setVisibility(View.GONE);
                HistorySalesActivity.this.cell_dept_level.setVisibility(View.GONE);
                HistorySalesActivity.this.cell_category_level.setVisibility(View.GONE);
            }
            //按类别
            else if( 3==(position+1))
            {
                HistorySalesActivity.this.cell_product.setVisibility(View.GONE);
                HistorySalesActivity.this.cell_barcode.setVisibility(View.GONE);
                HistorySalesActivity.this.cell_dept_code.setVisibility(View.VISIBLE);
                HistorySalesActivity.this.cell_dept_level.setVisibility(View.VISIBLE);
                HistorySalesActivity.this.cell_category_level.setVisibility(View.VISIBLE);

            }
            //其他
            else
            {
                HistorySalesActivity.this.cell_product.setVisibility(View.GONE);
                HistorySalesActivity.this.cell_barcode.setVisibility(View.GONE);
                HistorySalesActivity.this.cell_category_level.setVisibility(View.GONE);
                HistorySalesActivity.this.cell_dept_code.setVisibility(View.VISIBLE);
                HistorySalesActivity.this.cell_dept_level.setVisibility(View.VISIBLE);
                
            }
            
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent){
                Log.d(HistorySalesActivity.TAG, "select onNothing");
            }
        });
    }


    private void showDatePicker(String title,final EditText edittext){


        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DATE);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);

        // 添加大小月月份并将其转换为list,方便之后的判断
        String[] months_big = { "1", "3", "5", "7", "8", "10", "12" };
        String[] months_little = { "4", "6", "9", "11" };

        final List<String> list_big = Arrays.asList(months_big);
        final List<String> list_little = Arrays.asList(months_little);

        dialog = new Dialog(this);
        dialog.setTitle(title);
        // 找到dialog的布局文件
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.time_layout, null);

        // 年
        final WheelView wv_year = (WheelView) view.findViewById(R.id.year);
        wv_year.setAdapter(new NumericWheelAdapter(START_YEAR, END_YEAR));// 设置"年"的显示数据
        wv_year.setCyclic(true);// 可循环滚动
        wv_year.setLabel("年");// 添加文字
        wv_year.setCurrentItem(year - START_YEAR);// 初始化时显示的数据

        // 月
        final WheelView wv_month = (WheelView) view.findViewById(R.id.month);
        wv_month.setAdapter(new NumericWheelAdapter(1, 12));
        wv_month.setCyclic(true);
        wv_month.setLabel("月");
        wv_month.setCurrentItem(month);

        // 日
        final WheelView wv_day = (WheelView) view.findViewById(R.id.day);
        wv_day.setCyclic(true);
        // 判断大小月及是否闰年,用来确定"日"的数据
        if (list_big.contains(String.valueOf(month + 1))) {
            wv_day.setAdapter(new NumericWheelAdapter(1, 31));
        } else if (list_little.contains(String.valueOf(month + 1))) {
            wv_day.setAdapter(new NumericWheelAdapter(1, 30));
        } else {
            // 闰年
            if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
                wv_day.setAdapter(new NumericWheelAdapter(1, 29));
            else
                wv_day.setAdapter(new NumericWheelAdapter(1, 28));
        }
        wv_day.setLabel("日");
        wv_day.setCurrentItem(day - 1);

//        // 时
//        final WheelView wv_hours = (WheelView) view.findViewById(R.id.hour);
//        wv_hours.setAdapter(new NumericWheelAdapter(0, 23));
//        wv_hours.setCyclic(true);
//        wv_hours.setCurrentItem(hour);
//
//        // 分
//        final WheelView wv_mins = (WheelView) view.findViewById(R.id.mins);
//        wv_mins.setAdapter(new NumericWheelAdapter(0, 59, "%02d"));
//        wv_mins.setCyclic(true);
//        wv_mins.setCurrentItem(minute);

        // 添加"年"监听
        OnWheelChangedListener wheelListener_year = new OnWheelChangedListener() {
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                int year_num = newValue + START_YEAR;
                // 判断大小月及是否闰年,用来确定"日"的数据
                if (list_big.contains(String
                        .valueOf(wv_month.getCurrentItem() + 1))) {
                    wv_day.setAdapter(new NumericWheelAdapter(1, 31));
                } else if (list_little.contains(String.valueOf(wv_month
                        .getCurrentItem() + 1))) {
                    wv_day.setAdapter(new NumericWheelAdapter(1, 30));
                } else {
                    if ((year_num % 4 == 0 && year_num % 100 != 0)
                            || year_num % 400 == 0)
                        wv_day.setAdapter(new NumericWheelAdapter(1, 29));
                    else
                        wv_day.setAdapter(new NumericWheelAdapter(1, 28));
                }
            }
        };
        // 添加"月"监听
        OnWheelChangedListener wheelListener_month = new OnWheelChangedListener() {
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                int month_num = newValue + 1;
                // 判断大小月及是否闰年,用来确定"日"的数据
                if (list_big.contains(String.valueOf(month_num))) {
                    wv_day.setAdapter(new NumericWheelAdapter(1, 31));
                } else if (list_little.contains(String.valueOf(month_num))) {
                    wv_day.setAdapter(new NumericWheelAdapter(1, 30));
                } else {
                    if (((wv_year.getCurrentItem() + START_YEAR) % 4 == 0 && (wv_year
                            .getCurrentItem() + START_YEAR) % 100 != 0)
                            || (wv_year.getCurrentItem() + START_YEAR) % 400 == 0)
                        wv_day.setAdapter(new NumericWheelAdapter(1, 29));
                    else
                        wv_day.setAdapter(new NumericWheelAdapter(1, 28));
                }
            }
        };
        wv_year.addChangingListener(wheelListener_year);
        wv_month.addChangingListener(wheelListener_month);

        // 根据屏幕密度来指定选择器字体的大小
        int textSize = 0;

        textSize = 24;

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int mDensity = dm.densityDpi;

        if (dm.widthPixels >= 320 && dm.widthPixels<480 && dm.heightPixels >= 480 && dm.heightPixels<800) {
            textSize=20;
        }
        if (dm.widthPixels >= 480 && dm.widthPixels <= 720
                &&dm.heightPixels >= 800 && dm.heightPixels<=1280) {
            textSize=24;
        }
        if (dm.widthPixels >= 720 && dm.heightPixels >= 1280) {
            textSize=32;
        }
        if (dm.widthPixels >= 1000)
        {
            textSize=48;
        }


        wv_day.TEXT_SIZE = textSize;
 //     wv_hours.TEXT_SIZE = textSize;
 //     wv_mins.TEXT_SIZE = textSize;
        wv_month.TEXT_SIZE = textSize;
        wv_year.TEXT_SIZE = textSize;

        Button btn_sure = (Button) view.findViewById(R.id.btn_datetime_sure);
        Button btn_cancel = (Button) view
                .findViewById(R.id.btn_datetime_cancel);
        // 确定
        btn_sure.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                // 如果是个数,则显示为"02"的样式
                String parten = "00";
                DecimalFormat decimal = new DecimalFormat(parten);

                // 设置日期的显示
                // tv_time.setText((wv_year.getCurrentItem() + START_YEAR) + "-"
                // + decimal.format((wv_month.getCurrentItem() + 1)) + "-"
                // + decimal.format((wv_day.getCurrentItem() + 1)) + " "
                // + decimal.format(wv_hours.getCurrentItem()) + ":"
                // + decimal.format(wv_mins.getCurrentItem()));

                 edittext.setText((wv_year.getCurrentItem() + START_YEAR) + "-"
                 + decimal.format((wv_month.getCurrentItem() + 1)) + "-"
                 + decimal.format((wv_day.getCurrentItem() + 1))
                 );
                 //+ " "
                 //+ decimal.format(wv_hours.getCurrentItem()) + ":"
                 //+ decimal.format(wv_mins.getCurrentItem()));

                dialog.dismiss();
            }
        });
        // 取消
        btn_cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });
        // 设置dialog的布局,并显示
        dialog.setContentView(view);
        dialog.show();

    }



    @JavascriptInterface
    public String getjson() {
        String json="";
        json= WebServiceUtils.WS_HistorySale_json(
                this.deptid,
                Integer.toString( this.deptlevel ),
                this.categorylevel,
                search_product_code.getText().toString(),
                search_product_barcode.getText().toString(),
                this.search_startdate.getText().toString(),
                this.search_enddate.getText().toString(),
                this.showtype
                );
        return json;
    }

    @JavascriptInterface
    public String showtype() {
        return this.showtype;
    }

}
